package cn.tradewin.advisor.pages.master;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.EventContext;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.ajax.AjaxResponseRenderer;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.slf4j.Logger;

import cn.tradewin.advisor.commons.selectmodel.CodeLabelSelectModel;
import cn.tradewin.advisor.commons.util.CalendarUtil;
import cn.tradewin.advisor.commons.util.DatepickerSymbols;
import cn.tradewin.advisor.persist.model.Advcalendar;
import cn.tradewin.advisor.persist.model.CalendarDates;
import cn.tradewin.advisor.persist.services.CalendarService;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;

public class CalendarDetail {
	@Property
	private int r;
	
	@Property
	private int c;
	
	@Inject
	private Logger log;
	
	public String getMon() {
		return "mon" + (r*4 + c);
	}
	
	@Property
	private Advcalendar calendar;
	
	@Property
	private List<Advcalendar> calendars;
	
	@Property
	private List<CalendarDates> dates;
	
	@Property
	private String selectedDates;
	
	@Property
	private CalendarDates date;
	
	private String calendarId;
	
	@Property
	private CodeLabelSelectModel calendarModel;
	
	@Property
	private CodeLabelSelectModel categoryModel;
	
	@Property
	private String category;
	
	@Inject
    private AssetSource assetSource;
    
    @Inject
    @Symbol(DatepickerSymbols.JQUERY_CSS)
    private String css;
    
    @Inject
    @Symbol(DatepickerSymbols.JQUERY_LIBRARY)
    private String javascript;
    
    @Inject
    private ComponentResources resources;
    
    @Inject
    private AjaxResponseRenderer ajaxResponseRenderer;
    
    @Inject
	private Messages messages;
	
	@Inject
	private BeanModelSource beanModelSource;
	
	@Property
	private BeanModel<CalendarDates> beanModel;
	
	 @InjectComponent
	 private Zone datesZone;
	 
	 @Inject
	 private Request request;

	@Environmental
	JavaScriptSupport jss;
	
	void onActivate(EventContext context) {
		if (context == null) {
			calendarId = CalendarUtil.DEFAULT_CALENDAR;
		} else if (context.getCount() > 0) {
			calendarId = context.get(String.class, 0);
		}
	}
	
	String onPassivate() {
		return this.calendarId;
	}

	@Inject
	private CalendarService calendarService;
	
	void setupRender() {
		calendar = calendarService.getCalendar(calendarId);
//		dates = calendarService.getCalendarDates(calendarId);
		categoryModel = new CodeLabelSelectModel(calendarService.getCalendarCategory(calendar.getLocale()));
		
		beanModel = beanModelSource.createDisplayModel(CalendarDates.class, messages);
		beanModel.add("action", null);
		beanModel.include("date", "categoryName","startTime", "endTime", "action");
		beanModel.get("categoryName").sortable(false);
		beanModel.get("startTime").sortable(false);
		beanModel.get("endTime").sortable(false);
		beanModel.get("action").sortable(false);
	}
	
	void onPrepare() {
		if (this.calendar == null) {
			this.calendar = new Advcalendar();
		}
	}
	
	void onPrepareForRender() {
		dates = calendarService.getCalendarDates(calendarId);
	}
	
	void afterRender() {
//		dates = calendarService.getCalendarDates(this.calendarId);
//		JSONArray params = new JSONArray();
//		for (CalendarDates d : dates) {
//			JSONObject o = new JSONObject();
//			o.put(d.getDate(), d.getCategoryName());
//			params.put(o);
//		}
		Link url = resources.createEventLink("addHoliday");
		String surl = url.toAbsoluteURI();
		surl = surl.substring(0, surl.indexOf("?"));
		JSONObject params = new JSONObject();
		params.put("url", surl);
		jss.require("calendar/calendar").with(params);
		if ( ! DatepickerSymbols.NULL.equals(css)) {
			jss.importStylesheet(assetSource.getExpandedAsset(css));
		}
		if ( ! DatepickerSymbols.NULL.equals(javascript)) {
			jss.importJavaScriptLibrary(assetSource.getExpandedAsset(javascript));
		}
	}
	
	void onDelete(List<String> params) {
		calendarService.delCalendarDate(params.get(0), params.get(1));
	}
	
	
	void onAddHoliday(EventContext context) {
		String calendar = context.get(String.class, 0);
		String category = context.get(String.class, 1);
		String start = context.get(String.class, 2);
		String end = context.get(String.class, 3);
		
		int count = context.getCount(); 
		if (count > 4) {
			List<CalendarDates> adds = CollectionFactory.newList();
			for (int i = 4; i < context.getCount(); i++) {
				CalendarDates d = new CalendarDates();
				d.setCalendarId(calendar);
				d.setCategoryId(new Byte(category));
				d.setDate(context.get(String.class, i));
				d.setStartTime(start);
				d.setEndTime(end);
				adds.add(d);
				
			}
			Map<String, Object> dels = new HashMap<String, Object>();
			dels.put("calendarId", calendar);
			dels.put("dates", adds);
			calendarService.delCalendarDates(dels);
			calendarService.addCalendarDates(adds);
		}
		
		JSONArray array = new JSONArray();
		dates = calendarService.getCalendarDates(calendar);
		for (CalendarDates d : dates) {
			JSONObject o = new JSONObject();
			o.put("date", d.getDate());
			o.put("category", d.getCategoryName());
			o.put("start", d.getStartTime());
			o.put("end", d.getEndTime());
			array.put(o);
		}
		 if (request.isXHR()) {
	        ajaxResponseRenderer.addRender(datesZone);
	        log.info("*************is ajax request");
	     } else {
	    	 log.info("*************is not ajax request");
	     }
	}
	
	void onSuccess() {
		if (Strings.isNullOrEmpty(this.selectedDates)) return;
		List<String> dates = Splitter.on("/").splitToList(this.selectedDates);
		List<CalendarDates> adds = CollectionFactory.newList();
		for (String date : dates) {
			CalendarDates d = new CalendarDates();
			d.setCalendarId(calendar.getId());
			d.setCategoryId(new Byte(category));
			d.setDate(date);
			d.setStartTime(calendar.getStartTime());
			d.setEndTime(calendar.getEndTime());
			adds.add(d);
			
		}
		Map<String, Object> dels = new HashMap<String, Object>();
		dels.put("calendarId", calendar.getId());
		dels.put("dates", adds);
		calendarService.delCalendarDates(dels);
		calendarService.addCalendarDates(adds);
	}
}
